import { defineStore } from "pinia";
import {
  logout as userLogout,  
} from "@/api/modules/user"; //   login as userLogin,getUserInfo,
import type { LoginData, UserInfo } from "@/api/types/user";
import { removeToken } from "@/utils/auth";// , setToken
import { resetRouter } from "@/router";

export interface UserState {
  token: string;
  userInfo: UserInfo | null;
  roles: string[];
  permissions: string[];
}

export const useUserStore = defineStore("user", {
  state: (): UserState => ({
    token: "",
    userInfo: null,
    roles: [],
    permissions: [],
  }),

  getters: {
    // 是否已登录
    isLoggedIn: (state) => !!state.token,
    // 用户角色
    userRoles: (state) => state.roles,
    // 用户权限
    userPermissions: (state) => state.permissions,
    // 用户姓名
    userName: (state) => state.userInfo?.username || "",
    // 用户头像
    avatar: (state) => state.userInfo?.avatar || "",
  },

  actions: {
    /**
     * 用户登录
     * @param loginData 登录表单数据
     */
    async login(_loginData: LoginData) {
      try {
        // const { data } = await userLogin(loginData);
        // this.token = data.token;
        // setToken(data.token);
        return await this.getUserInfo();
      } catch (error) {
        return Promise.reject(error);
      }
    },

    /**
     * 获取用户信息
     */
    async getUserInfo() {
      try {
        // const { data } = await getUserInfo();
        // this.userInfo = data.userInfo;
        // this.roles = data.roles || [];
        // this.permissions = data.permissions || [];
        // return data;
      } catch (error) {
        return Promise.reject(error);
      }
    },
    async getUserList(_params: any = {}) {},
    /**
     * 用户登出
     */
    async logout() {
      try {
        await userLogout();
      } finally {
        this.resetState();
        removeToken();
        resetRouter();
      }
    },
    async updateUser(_id: string, _data: any = {}) {},
    async deleteUser(_id: string) {},
    async batchDeleteUsers(_ids: string[]) {},
    /**
     * 重置状态
     */
    resetState() {
      this.$reset();
    },

    /**
     * 检查权限
     * @param permission 权限标识
     */
    hasPermission(permission: string): boolean {
      return this.permissions.includes(permission);
    },

    /**
     * 检查角色
     * @param role 角色标识
     */
    hasRole(role: string): boolean {
      return this.roles.includes(role);
    },
  },

  // 开启持久化
  persist: {
    enabled: true,
    strategies: [
      {
        key: "user_store",
        storage: localStorage,
        paths: ["token"], // 只持久化token
      },
    ],
  },
});
